package com.mgkj.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mgkj.base.HttpResult;
import com.mgkj.common.constant.WmsConstants;
import com.mgkj.common.result.Result;
import com.mgkj.common.utils.HttpClientUtil;
import com.mgkj.common.utils.StringUtils;
import com.mgkj.common.utils.TimeUtils;
import com.mgkj.common.utils.yf.InitMoneyUtils;
import com.mgkj.dto.*;

import com.mgkj.dto.yf.*;
import com.mgkj.entity.*;
import com.mgkj.entity.session.*;
import com.mgkj.entity.yf.InitCoptg;
import com.mgkj.entity.yf.InitCopth;
import com.mgkj.mapper.*;
import com.mgkj.service.CommonService;
import com.mgkj.service.SaleService;
import com.mgkj.vo.*;
import com.mgkj.vo.yf.InitRaxVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;



import static com.mgkj.common.constant.WmsConstants.*;

/**
 * @author yyyjcg
 * @date 2024/4/15
 * @Description
 */
@Service
@Slf4j
public class SaleServiceImpl implements SaleService {
    @Resource
    private SaleMapper saleMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private DscmbMapper dscmbMapper;
    @Resource
    private InitCoptgMapper initCoptgMapper;

    @Resource
    private InitCopthMapper initCopthMapper;

    @Resource
    private CommonService commonService;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private EnterStorageMapper enterStorageMapper;

    @Resource
    private InvmbMapper invmbMapper;

    @Resource
    private WmsInvlaMapper wmsInvlaMapper;

    @Resource
    private WmsInvmlMapper wmsInvmlMapper;



//=====================================================易飞接口代码============================================//

    @Override
    public Result salesSlipByOrder(InitSalesSlipDto initSalesSlipDto) throws IOException {
        DynamicDataSourceContextHolder.push(initSalesSlipDto.getCompany());
        boolean flag = false;
        String dh = "";
        InitCoptg coptg = new InitCoptg();
        Double ybxhje = 0.0;
        Double ybxhse = 0.0;
        Double bbxhje = 0.0;
        Double bbxhse = 0.0;
        //查询数据库中是否存在已审核核的相同单据号的销货单
        Integer count = initCoptgMapper.selectCount(new QueryWrapper<InitCoptg>()
                .eq("TG001", initSalesSlipDto.getTG001())
                .eq("TG002", initSalesSlipDto.getTG002())
                .eq("TG023", "Y"));
        if (count >= 1) {
            return Result.fail("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据!").message("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据!");
        }
        Dscmb dscmb = dscmbMapper.selectOne(new QueryWrapper<Dscmb>().eq("MB003", initSalesSlipDto.getCompany()));
        String company = dscmb.getMB001().trim();
        //查询数据库中是否存在未审核的相同单据号的销货单
        Integer count1 = initCoptgMapper.selectCount(new QueryWrapper<InitCoptg>()
                .eq("TG001", initSalesSlipDto.getTG001())
                .eq("TG002", initSalesSlipDto.getTG002())
                .eq("TG023", "N"));
        if (count1 >= 1) {
            dh = initSalesSlipDto.getTG002();
            initCoptgMapper.delete(new QueryWrapper<InitCoptg>()
                    .eq("TG001", initSalesSlipDto.getTG001())
                    .eq("TG002", initSalesSlipDto.getTG002()));
            initCopthMapper.delete(new QueryWrapper<InitCopth>()
                    .eq("TH001", initSalesSlipDto.getTG001())
                    .eq("TH002", initSalesSlipDto.getTG002()));
        } else {
//            Integer count2 =  initCoptgMapper.selectCount(new QueryWrapper<InitCoptg>()
//                    .eq("UDF12", initSalesSlipDto.getTG002()));
//            if (count2 >= 1) {
//                return Result.fail("此单号已存在");
//            } else {
            flag = true;
            dh = commonService.getIdByType(initSalesSlipDto.getTG001(), "COPTG");
            coptg.setUdf12(initSalesSlipDto.getTG002());
//            }
        }

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter create_date = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        // 格式化时间
        String formattedTime = currentTime.format(formatter);
        String yyyyMMdd = currentTime.format(formatter1);

        coptg.setCompany(company);
        String creator = initSalesSlipDto.getCreateBy();
        if(StringUtils.isEmpty(creator)) {
            return Result.fail("抓不到登录信息，请重新登录.").message("抓不到登录信息，请重新登录.");
        }
//        String creator = initSalesSlipDto.getTG006();
//        String userGroup = initSalesSlipDto.getTG005();
        coptg.setCreator(creator);
        String userGroup = commonMapper.getUsrGroup(creator);
        //查询ADMMF-用户信息，MF004组编号
//        coptg.setUsrGroup("DS");
        coptg.setUsrGroup(userGroup);
        coptg.setCreateDate(currentTime.format(create_date));
        coptg.setFlag("2");
        coptg.setTg001(initSalesSlipDto.getTG001());
        coptg.setTg002(dh);
        coptg.setTg003(currentTime.format(formatter1));
        coptg.setTg004(initSalesSlipDto.getTG004());
        coptg.setTg005(initSalesSlipDto.getTG005());
        coptg.setTg006(initSalesSlipDto.getTG006());
        coptg.setTg009(initSalesSlipDto.getTG009());
        initSalesSlipDto.setTG002(dh);
        //4、设置销货单头税率等数据
        //设置币种
        coptg.setTg011(initSalesSlipDto.getTG011());
        Double hl = 0.0;
        System.out.println("TG011: " + initSalesSlipDto.getTG011()); // 确认是否为"RMB"
        if (initSalesSlipDto.getTG011() == null) {
            System.out.println("TG011为null！");
        }
        if (initSalesSlipDto.getTG011().trim().equals("RMB")) {
            coptg.setTg012(1.0000000);
        } else {
            hl = enterStorageMapper.selectHL(initSalesSlipDto.getTG011());
            coptg.setTg012(hl);
        }
        //发票种类待定
        coptg.setTg016("A");
        coptg.setTg017(initSalesSlipDto.getTG017());
        //打印次数
        coptg.setTg022(0.0);
        //审核码/更新码
        coptg.setTg023("N");
        coptg.setTg024("N");
        //单据日期
        coptg.setTg042(yyyyMMdd);
        List<InitCopth> copths = new ArrayList<>();

        Double Tn033 = 0.0;
        int xh = 1;
        for (InitSalesSlipBodyDto initSalesSlipBodyDto : initSalesSlipDto.getInitSalesSlipBodyDtos()) {
            initSalesSlipBodyDto.setTH002(dh);
            InitCopth copth = new InitCopth();
            copth.setCompany(company);
            copth.setCreator(creator);
            copth.setUsrGroup(userGroup);
//            copth.setUsrGroup(commonMapper.getUsrGroup("MES"));
            copth.setCreateDate(currentTime.format(create_date));
            copth.setFlag("2");
            copth.setTh001(initSalesSlipBodyDto.getTH001());
            copth.setTh002(dh);
            copth.setTh003(String.format("%04d", xh));   // 序号前端传的都是0001，后端自己重新算
            xh++;
            copth.setTh004(initSalesSlipBodyDto.getTH004());
            Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().eq("MB001", initSalesSlipBodyDto.getTH004()));
            copth.setTh005(invmb.getMb002());
            copth.setTh006(invmb.getMb003());
// 仓库
            copth.setTh007(initSalesSlipBodyDto.getTH007());
// 数量
            Double sl = initSalesSlipBodyDto.getTH008();
            Double dj = initSalesSlipBodyDto.getTH012();
            Double je = sl * dj;
            copth.setTh008(sl);
// 单位
            copth.setTh009(initSalesSlipBodyDto.getTH009());
            copth.setTh010(0D);
// 单价
            copth.setTh012(dj);
// 订单单别
            copth.setTh014(initSalesSlipBodyDto.getTH014());
// 订单单号
            copth.setTh015(initSalesSlipBodyDto.getTH015());
// 订单序号
            copth.setTh016(initSalesSlipBodyDto.getTH016());
// 批号
            copth.setTh017(initSalesSlipBodyDto.getTH017());
 //审核码（可选Y:已审核/N:未审核/V:作废）
            copth.setTh020("N");
// 更新码（可选Y/N）
            copth.setTh021("N");
// 折扣率
            copth.setTh025(1.0);
            copth.setTh024(initSalesSlipBodyDto.getTH024());
// 开票码（可选Y/N）
            copth.setTh026("N");
// 类型（可选1.赠品量/2.备品量）
            copth.setTh031("1");

            InitRaxDto initRaxDto = new InitRaxDto(initSalesSlipDto.getTG017(),//税种
                    BigDecimal.valueOf(initSalesSlipBodyDto.getTH008()),//数量
                    BigDecimal.valueOf(initSalesSlipDto.getTG044()),//税率
                    BigDecimal.valueOf(initSalesSlipBodyDto.getTH012()),//单价
                    BigDecimal.valueOf(initSalesSlipDto.getTG012()));//汇率
            InitRaxVo rax = InitMoneyUtils.getRax(initRaxDto);
            //原币销货金额
//                    coptg.setTg013(coptg.getTg013() - copth.getTh035() + rax.getPriceBeforeTax().doubleValue());
            ybxhje += rax.getPriceBeforeTax().doubleValue();
            copth.setTh035(rax.getPriceBeforeTax().doubleValue());
            //原币销货税额
//                    coptg.setTg025(coptg.getTg025() - copth.getTh036()+ rax.getTaxPrice().doubleValue());
            ybxhse += rax.getTaxPrice().doubleValue();
            copth.setTh036(rax.getTaxPrice().doubleValue());
            //本币销货金额
//                    coptg.setTg045(coptg.getTg045() - copth.getTh037() + rax.getPriceBeforeTaxLocal().doubleValue());
            bbxhje += rax.getPriceBeforeTaxLocal().doubleValue();
            copth.setTh037(rax.getPriceBeforeTaxLocal().doubleValue());
            //本币销货税额
//                    coptg.setTg046(coptg.getTg046() - copth.getTh038() + rax.getTaxPriceLocal().doubleValue());
            bbxhse += rax.getTaxPriceLocal().doubleValue();
            copth.setTh038(rax.getTaxPriceLocal().doubleValue());
            // 金额
            copth.setTh013(rax.getPrice().doubleValue());

// 已开票数量
//            copth.setTh042(sl);
// 件装-TO012

            copth.setTh043(initSalesSlipBodyDto.getTH043());
// 件数-TO013
            copth.setTh044(initSalesSlipBodyDto.getTH044());
// 出货通知单别
            copth.setTh045(initSalesSlipBodyDto.getTH045());
// 出货通知单号
            copth.setTh046(initSalesSlipBodyDto.getTH046());
// 出货通知序号
            copth.setTh047(initSalesSlipBodyDto.getTH047());
// 税率（默认值9.9999）
            copth.setTh048(initSalesSlipDto.getTG044());
// 库位
//            copth.setTh056(initSalesSlipBodyDto.getTH056());
            copth.setTh056("##########");
// 分期合同（默认值'N'，可选Y/N）
//            copth.setTh064("N");

// 检核确认（默认值'N'，可选Y/N）
//            copth.setThh01("N");

            copths.add(copth);
            Tn033 += initSalesSlipBodyDto.getTH008();
        }
        coptg.setTg010(initSalesSlipDto.getTG010());
//        coptg.setTg010("1000");
        //原币销货金额
        coptg.setTg013(ybxhje);
        //原币销货税额
        coptg.setTg025(ybxhse);
        //本币销货金额
        coptg.setTg045(bbxhje);
        //本币销货税额
        coptg.setTg046(bbxhse);
//        //件数
//        coptg.setTg032();
//        //总数量
        coptg.setTg033(Tn033);
//        coptg.setTg033(Tn033);
        //烟酒注记
        coptg.setTg031("N");
        //生成分录(收入)
        //生成分录(成本)
        coptg.setTg036("N");
        coptg.setTg037("N");
        //审核者
//        coptg.setTg043("MES");
        //税率
        coptg.setTg044(initSalesSlipDto.getTG044());
        //总包装数量
//        coptg.setTg054(Tn034);
        //签核状态码
        coptg.setTg055("N");
        //抛转状态
        coptg.setTg059("N");
        //EBC汇出码
        coptg.setTg068("N");
        //超限放行
        coptg.setTg074("N");


        //插入易飞单头单身表
        initCoptgMapper.insert(coptg);
        for (InitCopth copth : copths) {
            initCopthMapper.insert(copth);
        }

        Integer i = initCopthMapper.selectCount(new QueryWrapper<InitCopth>().eq("TH001", initSalesSlipDto.getTG001())
                .eq("TH002", dh));
        if (i == null || i <= 0) {
            initCoptgMapper.delete(new QueryWrapper<InitCoptg>().eq("TG001", initSalesSlipDto.getTG001())
                    .eq("TH002", dh));
            return Result.fail("单身生成失败！").message("单身生成失败！");
        }

//        Integer countTg = initCoptgMapper.selectCount(new QueryWrapper<InitCoptg>()
//                .eq("TG001", initSalesSlipDto.getTG001())
//                .eq("TG002", dh));
//        if (countTg == null || countTg <= 0) {
//            return Result.fail("COPTG生成失败！").message("COPTG生成失败！");
//        }
        ShenHe shenHe = new ShenHe();
        shenHe.setCom(company);
        shenHe.setProgram("COPI08");
        shenHe.setUser(creator);
        shenHe.setDb(initSalesSlipDto.getTG001());
        shenHe.setDh(dh);
        shenHe.setType("DO");
        shenHe.setRq(currentTime.format(formatter1));
        InetAddress localhost = InetAddress.getLocalHost();
//        String ipAddress = localhost.getHostAddress();
//        String url = "http://" + ipAddress + ":9000/api/yifei/audit";
        String url = "http://" + "192.168.0.141" + ":9000/api/yifei/audit";
//        String url = "http://" + "192.168.0.141" + ":9000/api/yifei/audit";
        String jsonString = JSON.toJSONString(shenHe);
        System.out.println(jsonString);
        String ans = null;
        try {
//            ShenHe anss=restTemplate.postForObject(url,shenHe,ShenHe.class);
            ans = HttpClientUtil.postRequest(url, jsonString);
        } catch (Exception e) {
//            if (flag) {
//                initCoptgMapper.deleteCoptg(coptg);
//                for (InitCopth copth1 : copths) {
//                    initCopthMapper.deleteCopth(copth1);
//                }
//            }
            log.info("出现异常请查看审批后台是否开启");
            return Result.fail().message(e.getMessage());
        }
        HttpResult httpResult = new HttpResult();

        if (ans == null) {

                initCoptgMapper.deleteCoptg(coptg);
                for (InitCopth copth1 : copths) {
                    initCopthMapper.deleteCopth(copth1);
                }

            return Result.fail().message("出现异常请查看审批后台是否开启!");
        } else {
            httpResult = JSON.parseObject(ans, HttpResult.class);
            System.out.println("httpResult: " + httpResult);
        }
        if (httpResult.getStatus().equals("失败")) {

                initCoptgMapper.deleteCoptg(coptg);
                for (InitCopth copth1 : copths) {
                    initCopthMapper.deleteCopth(copth1);
                }

            return Result.fail(httpResult.getReason() + httpResult.getDetail());
        }

        Boolean b=this.wmsinsertCoptg(initSalesSlipDto,initSalesSlipDto.getTG001());
        if (!b) {
                initCoptgMapper.deleteCoptg(coptg);
                for (InitCopth copth1 : copths) {
                    initCopthMapper.deleteCopth(copth1);
                }

                return Result.fail().message("wms_invla和wms_invml插入失败！");

            }
        return Result.ok("单据生成成功:" + initSalesSlipDto.getTG001() + '_' + initSalesSlipDto.getTG002());
//        return null;
    }

    @Transactional
    public Boolean wmsinsertCoptg(InitSalesSlipDto coptg, String tg001){
        List<WmsInvml> invmlList=new ArrayList<>();
        List<WmsInvla> wmsInvlas=new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        // 将 LocalDateTime 对象格式化为字符串
        String formattedDateTime = now.format(formatter2);
        String creator= coptg.getCreator();
        String userGroup= coptg.getUserGroup();
        String company= coptg.getCompany();
        boolean result = true;
        for (InitSalesSlipBodyDto copth : coptg.getInitSalesSlipBodyDtos()){
            //库位可以不存在
            if (copth.getKwInfo() == null || copth.getKwInfo().isEmpty()) {
                result = insertByKw(now,formattedDateTime,copth,invmlList,wmsInvlas,creator,userGroup,company,tg001);
            } else {
                for (KWAndNum kwAndNum : copth.getKwInfo()) {
                    copth.setTH056(kwAndNum.getKw());
                    copth.setTH008(kwAndNum.getNum());
                    result = insertByKw(now,formattedDateTime,copth,invmlList,wmsInvlas,creator,userGroup,company,tg001);
                    if (!result) return result;
                }
            }
            if (!result) return result;
        }
        return true;
    }

    @Override
    public List<Map<String, Object>> getCustomOrder(String startTime, String endTime, String company) {
        DynamicDataSourceContextHolder.push(company);
        return saleMapper.getCustomOrder(startTime,endTime,company);
    }

    /**
     * 根据库位插入信息
     */
    private boolean insertByKw(LocalDateTime now, String formattedDateTime, InitSalesSlipBodyDto copth, List<WmsInvml> invmlList, List<WmsInvla> wmsInvlas,
                               String creator,String userGroup,String company,String tg001) {
        Double t = 0.0;
        WmsInvla wmsInvla1 = wmsInvlaMapper.selectOne(new QueryWrapper<WmsInvla>()
                .eq("LA005", -1.0)
                .eq("LA006", copth.getTH001())//单别
                .eq("LA007", copth.getTH002())//单号
                .eq("LA008", copth.getTH003())//序号
                .eq("LA023", copth.getTH056())//库位
                .eq("LA009", copth.getTH007())//仓库
                .eq("LA016", copth.getTH017()));//批号
        if (wmsInvla1 != null) {
            t = wmsInvla1.getLa011() - copth.getTH008();
            wmsInvla1.setLa011(t);//把交易明细信息档里的库存量叠加

            int i = wmsInvlaMapper.update(wmsInvla1, new QueryWrapper<WmsInvla>()
                    .eq("LA005", -1.0)
                    .eq("LA006", copth.getTH001())//单别
                    .eq("LA007", copth.getTH002())//单号
                    .eq("LA008", copth.getTH003())//序号
                    .eq("LA023", copth.getTH056())//库位
                    .eq("LA009", copth.getTH007())//仓库
                    .eq("LA016", copth.getTH017()));//批号
            if (i != 1) {
                return false;
            }
        } else {
            WmsInvla wmsInvla = new WmsInvla();
            wmsInvla.setCompany(company);
            wmsInvla.setCreator(creator);
            wmsInvla.setUsrGroup(userGroup);
            wmsInvla.setCreateDate(formattedDateTime);
//            wmsInvla.setModifier(copth.getModifier());
//            wmsInvla.setModiDate(copth.getModiDate());
            wmsInvla.setFlag(1.0);
            wmsInvla.setLa001(copth.getTH004());//品号
            wmsInvla.setLa004(TimeUtils.HZStdTime());//日期
//            这四位不能重复
            wmsInvla.setLa005(-1.0);//按单据性质的库存影响:减 或 调拨单性质的出写入为-1，其余为+1。
            wmsInvla.setLa006(copth.getTH001());//单别
            wmsInvla.setLa007(copth.getTH002());//单号
            wmsInvla.setLa008(copth.getTH003());//序号
            wmsInvla.setLa009(copth.getTH007());//仓库
            wmsInvla.setLa010(copth.getTH014());//备注
            wmsInvla.setLa011(copth.getTH008());//单据交易库存数量
            wmsInvla.setLa012(0.0);
            wmsInvla.setLa013(0.0);
            wmsInvla.setLa014("2");
            wmsInvla.setLa015("");
            wmsInvla.setLa016(copth.getTH017());//批号
            wmsInvla.setLa017(0.0);
            wmsInvla.setLa018(0.0);
            wmsInvla.setLa019(0.0);
            wmsInvla.setLa020(0.0);
            wmsInvla.setLa021(0.0);
            wmsInvla.setLa022(TimeUtils.HZStdTime());//审核时间
            wmsInvla.setLa023(copth.getTH056());//库位
            wmsInvla.setLa024("");
            wmsInvla.setUdf01("销货单生成");
            wmsInvlas.add(wmsInvla);
            wmsInvlaMapper.insert(wmsInvla);
        }
        // INVML的修改
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = now.format(formatter1);
        WmsInvml wmsInvml = new WmsInvml();
        wmsInvml = wmsInvmlMapper.selectOne(new QueryWrapper<WmsInvml>()
                .eq("ML001", copth.getTH004())//品号
                .eq("ML002", copth.getTH007())//仓库
                .eq("ML003", copth.getTH056())//库位
                .eq("ML004", copth.getTH017()));//批号
        if (wmsInvml == null) {
            wmsInvml = new WmsInvml();
            wmsInvml.setCompany(company);
            wmsInvml.setCreator(creator);
            wmsInvml.setUsrGroup(userGroup);
            wmsInvml.setCreateDate(formattedDateTime);
//                wmsInvml.setModifier(copth.getModifier());
//                wmsInvml.setModiDate(copth.getModiDate());
            wmsInvml.setFlag(1.0);
            wmsInvml.setMl001(copth.getTH004());//品号
            wmsInvml.setMl002(copth.getTH007());//仓库
            wmsInvml.setMl003(copth.getTH056());//库位
            wmsInvml.setMl004(copth.getTH017());//批号
            wmsInvml.setMl005(copth.getTH008());//库存数量
            wmsInvml.setMl006(copth.getTH008());//库存包装数量
            wmsInvml.setMl009(formattedDate);//日期
            String uuid = UUID.randomUUID().toString();
            wmsInvml.setUdf12(uuid);
            int i1 = wmsInvmlMapper.insert(wmsInvml);
            if (i1 != 1) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        } else {
            invmlList.add(wmsInvml);
            if ("23".equals(tg001.substring(0, 2))) {//单据
                t = wmsInvml.getMl005() - copth.getTH008();
                wmsInvml.setMl005(t);//把品号信息档里的库存量减掉销货量
            }
            int i2 = wmsInvmlMapper.update(wmsInvml, new QueryWrapper<WmsInvml>()
                    .eq("ML001", wmsInvml.getMl001())
                    .eq("ML002", wmsInvml.getMl002())
                    .eq("ML003", wmsInvml.getMl003())
                    .eq("ML004", wmsInvml.getMl004()));
            if (i2 != 1) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        return true;
    }












    //=====================================================E10接口代码============================================//
    /**
     * 订单下架查询简洁的信息
     * @param dto
     * @return
     */
    @Override
    public Result ListSaleOrderOutStock(ListSaleOrderOutStockDto dto) {
        try {
            List<ListSaleOrderOutStockVo> list = saleMapper.ListSaleOrderOutStock(dto);
            if (!list.isEmpty()){
                return Result.ok(list).message("成功");
            }else {
                return Result.fail().message("暂无数据");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("失败");
        }

    }

    /**
     * 订单下架根据单号查询详情
     * @param docNo
     * @return
     */
    @Override
    public Result ListSaleOrderOutStockDetail(String docNo) {
        try {
            List<ListSaleOrderOutStockDetailVo> list = saleMapper.ListSaleOrderOutStockDetail(docNo);
            if (!list.isEmpty()){
                return Result.ok(list).message("成功");
            }else {
                return Result.fail().message("暂无数据");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("失败");
        }
    }

    /**
     * 通知下架--查询
     * @param dto
     * @return
     */
    @Override
    public Result ListNoticeOutStock(ListNoticeOutStockDto dto) {
        try {
            List<ListNoticeOutStockVo> list = saleMapper.ListNoticeOutStock(dto);
            if (!list.isEmpty()){
                return Result.ok(list).message("成功");
            }else {
                return Result.fail().message("暂无数据");
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            return Result.fail().message("失败");
        }
    }

    /**
     * 通知下架--汇总查询
     * @param docNo
     * @return
     */
    @Override
    public Result ListNoticeOutStockDetail(String docNo) {
        try {
            List<ListNoticeOutStockDetailVo> list = saleMapper.ListNoticeOutStockDetail(docNo);
            if (!list.isEmpty()){
                return Result.ok(list).message("成功");
            }else {
                return Result.fail(list).message("暂无数据");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("失败");
        }
    }

//    /**
//     * 通知下架--同步中间表
//     * @param list
//     * @return
//     */
//    @Override
//    public MiddleReturnDto OtherOutStockInsertMiddleTable(List<NoticeOutStockSubmitDto> list) {
//        DateTime date = DateUtil.date();
//        List<String> docNo = new ArrayList<>();
//        for (NoticeOutStockSubmitDto dto : list) {
//            String barcode = dto.getBarcode();
//            docNo.add(dto.getDocNo());
//            saleMapper.insertMiddleTable(new Lsmdt(
//                    UUID.randomUUID().toString().toUpperCase(),                               //主键
//                    barcode,                             //条码编号
//                    dto.getWarehouseCode(),              //仓库
//                    dto.getBinCode(),                    //库位
//                    barcode.substring(barcode.indexOf("#")+1),                    //批号
//                    dto.getMatchQty(),                   //异动数量
//                    -1,                                   //异动类型
//                    dto.getDocNo(),                      //来源单号
////                "0",                                   //来源项次
////                null,                                  //目的单号
////                "0",                                   //目的项次
//                    "admin",                             //PDA操作人代号
//                    DateUtil.format(date,"yyyy-MM-dd"),              //扫描日期
//                    DateUtil.format(date,"HH:mm:ss.SSS"),               //时间
//                    "Y",                                 //扣账资料否
//                    dto.getUnitNo(),                     //异动数量单位
//                    1.0,                                 //异动与库存单位换算率
//                    NOTICEOUTSTOCK_APPID,                 //终端设备编号
//                    NOTICEOUTSTOCK_APPID+NOTICEOUTSTOCK_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddhhmmss"),  //APP申请串号
//                    NOTICEOUTSTOCK_APPMODULE,                   //APP申请所属模组
//                    "N",                                 //ERP异动码
//                    dto.getRemark(),                    //备注
//                    "",                                 //条码异动类型
//                    UUID.randomUUID().toString().trim().replace("-",""),//APP申请序列号
//                    "002",                              //039
//                    "YNY",                              //042
//                    dto.getUnitNo(),                   //046
//                    "0",                                //047
//                    0.00,
//                    0.00,
//                    "9998-12-31",                       //058
//                    dto.getItemCode(),                   //物料代码
//                    UUID.randomUUID().toString().trim().replace("-",""),//字符保留栏位
//                    DateUtil.format(DateUtil.date(),"yyyy-MM-dd"),                 //过账日期
//                    DateUtil.format(DateUtil.date(),"yyyy-MM-dd"),                 //日期保留栏位
//                    DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"), //资料创建日
//                    "1",                                //资料建立者
//                    WMS_ENTID,                          //企业代码
//                    DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"),//最近修改日
//                    "1",                                //资料修改者
//                    "qqq",                              //资料所属部门
//                    "dcms",                             //资料所有者
//                    WMS_COMPANYID,                      //营运据点
//                    "Y"                                //状态码
//            ));
//        }
//        return new MiddleReturnDto(docNo.get(0),NOTICEOUTSTOCK_APPID,NOTICEOUTSTOCK_APPID+NOTICEOUTSTOCK_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddhhmmss"),"");
//    }

    /**
     * 通知下架提交
     * @param middleReturnDto
     * @return
     */
    @Override
    public JSONObject OtherOutStockSubmit(MiddleReturnDto middleReturnDto) {
        EtenSession etenSession = new EtenSession(WMS_SUBMIT_KEY,WMS_TYPE,
                new SessionHost(WMS_HOST_PROD,WMS_HOST_IP,WMS_HOST_LANG,WMS_HOST_ACCT, middleReturnDto.getTimestamp(), middleReturnDto.getErpRemark()),
                new SessionService(WMS_SERVICE_PROD,NOTICEOUTSTOCK_NAME,WMS_SERVICE_IP,WMS_SERVICE_ID),
                new SessionDatakey(WMS_ENTID,WMS_COMPANYID),
                new SessionPayload(new StdData(new ScanToStorageParameter(
                        "","","","","","","","","","","","","","",
                        new ScanToStorageParameterData(
                                "", middleReturnDto.getDocNo(), middleReturnDto.getDocNo(), "","","","","","","","","","","","",""
                        ),
                        new ScanToStorageParameterHost(
                                WMS_HOST_ACCT, middleReturnDto.getTimestamp(), middleReturnDto.getAppid(),NOTICEOUTSTOCK_APPMODULE,WMS_APPVERSION,NOTICEOUTSTOCK_NAME,WMS_ENTID,WMS_COMPANYID,middleReturnDto.getErpRemark(),"0",""
                        )
                ))));
        System.out.println(etenSession);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type","text/plain; charset=utf-8");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(etenSession), httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(SERVICE_IP_PORT+"/Restful/invokeSrv", httpEntity, String.class);
        JSONObject result = JSON.parseObject(response);
        return result;
    }

    @Override
    public Result ListSaleReturn(ListSaleReturnDto dto) {
        try {
            List<ListSaleReturnVo> list = saleMapper.ListSaleReturn(dto);
            if (!list.isEmpty()){
                return Result.ok(list).message("成功");
            }else {
                return Result.fail().message("暂无数据");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("失败");
        }
    }

    @Override
    public Result ListSaleReturnDetail(String docNo) {
        List<ListSaleReturnDetailVo> list = saleMapper.ListSaleReturnDetail(docNo);
        return Result.ok(list);
    }

    @Override
    public MiddleReturnDto SaleReturnInsertMiddleTable(List<SaleReturnSubmitDto> list) {
        DateTime date = DateUtil.date();
        List<String> docNo = new ArrayList<>();
        for (SaleReturnSubmitDto dto : list) {
            String barcode = dto.getBarcode();
            docNo.add(dto.getDocNo());
            saleMapper.insertMiddleTable2(Lsmdt.builder()
                            .lsmdTId(UUID.randomUUID().toString().toUpperCase()) //主键
                            .lsmd001(barcode)      //条码编号
                            .lsmd002(dto.getWarehouseCode())      //仓库
                            .lsmd003(dto.getBinCode())//库位
                            .lsmd004(barcode.substring(barcode.indexOf("#")+1))//批号
//                    达威联调时wms与e10的批号管理不一致，先全改为* /""
//                            .lsmd004("")//批号
                            .lsmd005(dto.getMatchQty())//异动数量
                            .lsmd006(1)//异动类型
                            .lsmd007(dto.getDocNo())//来源单号
                            .lsmd008("0")
                            .lsmd010("0")
                            .lsmd013("admin")//PDA操作人代号
                            .lsmd014(DateUtil.format(date,"yyyy-MM-dd"))//扫描日期
                            .lsmd015(DateUtil.format(date,"HH:mm:ss.SSS"))//时间
                            .lsmd019("Y")//扣账资料否
                            .lsmd024(dto.getUnitCode())//异动数量单位
                            .lsmd025(1.0)//异动与库存单位换算率
                            .lsmd026(SALERETURN_APPID)//终端设备编号
                            .lsmd027(SALERETURN_APPID+SALERETURN_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddhhmmss"))//APP申请串号
                            .lsmd028(SALERETURN_APPMODULE)//APP申请所属模组
                            .lsmd029("N")//ERP异动码
                            .lsmd030("")//备注
                            .lsmd031("1")//条码异动类型
                            .lsmd033(UUID.randomUUID().toString().trim().replace("-",""))//APP申请序列号
//                    .lsmd037(barcode.substring(barcode.indexOf("#")+1))
//                    达威联调时wms与e10的批号管理不一致，先全改为* /""
                            .lsmd034("2001")
                            .lsmd036("")
                            .lsmd037("")
                            .lsmd038("")
                            .lsmd039("002")
                            .lsmd042("YNY")
                            .lsmd045("0.0")
                            .lsmd046(dto.getUnitCode())
                            .lsmd047("0.0")
                            .lsmd053(0.00)
                            .lsmd054("0.00")
                            .lsmd055(0.00)
                            .lsmd058("9998-12-31")
                            .lsmd081("0.0")
                            .lsmd082("0.0")
                            .lsmd083(dto.getItemCode())
                            .lsmd084(UUID.randomUUID().toString().trim().replace("-",""))//字符保留栏位
                            .lsmd085(DateUtil.format(DateUtil.date(),"yyyy-MM-dd"))//过账日期
                            .lsmd086(DateUtil.format(DateUtil.date(),"yyyy-MM-dd"))//日期保留栏位
                            .lsmd906("0")
                            .lsmd907("0")
                            .lsmdcrtdt(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"))//资料创建日
                            .lsmdcrtid("1")//资料建立者
                            .lsmdent(WMS_ENTID)//企业代码
                            .lsmdmoddt(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"))//最近修改日
                            .lsmdmodid("1") //资料修改者
                            .lsmdowndp("qqq") //资料所属部门
                            .lsmdownid("dcms") //资料所有者
                            .lsmdsite(WMS_COMPANYID) //营运据点
                            .lsmdstus("Y") //状态码
                            .build()
            );
        }
        return new MiddleReturnDto(docNo.get(0),SALERETURN_APPID,SALERETURN_APPID+SALERETURN_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddhhmmss"),"");
    }

    @Override
    public JSONObject SaleOutStockSubmit(MiddleReturnDto middleReturnDto) {
        EtenSession etenSession = new EtenSession(WMS_SUBMIT_KEY,WMS_TYPE,
                new SessionHost(WMS_HOST_PROD,WMS_HOST_IP,WMS_HOST_LANG,WMS_HOST_ACCT, middleReturnDto.getTimestamp(), ""),
                new SessionService(WMS_SERVICE_T100,SALEOUTSTOCK_NAME,WMS_SERVICE_IP,WMS_SERVICE_ID),
                new SessionDatakey(WMS_ENTID,middleReturnDto.getWmsCompanyid()),
                new SessionPayload(new StdData(new ScanToStorageParameter(
                        "","","","","","","","","","","","","","",
                        new ScanToStorageParameterData(
                                "", middleReturnDto.getDocNo(), middleReturnDto.getDocNo(), "","","","","","","","","","","","",""
                        ),
                        new ScanToStorageParameterHost(
                                WMS_HOST_ACCT, middleReturnDto.getTimestamp(), middleReturnDto.getAppid(),SALEOUTSTOCK_APPMODULE,WMS_APPVERSION,SALEOUTSTOCK_NAME,WMS_ENTID,middleReturnDto.getWmsCompanyid(),middleReturnDto.getErpRemark(),"0",""
                        )
                ))));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type","text/plain; charset=utf-8");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(etenSession), httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(SERVICE_IP_PORT+"/Restful/invokeSrv", httpEntity, String.class);
//        System.out.println(httpEntity);
        System.out.println(response);
        System.out.println(httpEntity.getBody());
        JSONObject result = JSON.parseObject(response);
        return result;
    }

    @Override
    public MiddleReturnDto SaleOrderOutStockInsertMiddleTable(List<SaleOrderOutDto> list) {
        System.out.println("同步中间表");
        DateTime date = DateUtil.date();
        List<String> docNo = new ArrayList<>();
        for (SaleOrderOutDto dto : list) {
            // 查询是否启用了批号管理
            boolean isLotControlEnabled = itemMapper.selectCount(
                    new LambdaQueryWrapper<Item>()
                            .eq(Item::getItemCode, dto.getItemCode())
                            .ne(Item::getLotControl, "N")
            ) > 0;

            // 查询是否启用了库位管理
            boolean isBinControlEnabled = itemMapper.selectBinControl(dto.getItemCode()) == 1;

            System.out.println("商品：" + dto.getItemCode() + " 批号管理：" + isLotControlEnabled + " 库位管理：" + isBinControlEnabled);

            // 解析条码
            String barcode = dto.getBarcode();
            docNo.add(dto.getDocNo());

            // 处理批号和库位逻辑
            String lotNumber = "";
            String binCode = dto.getBinCode();
            if (barcode.contains("#")) {
                lotNumber = barcode.substring(barcode.indexOf("#") + 1);
            }

            saleMapper.insertMiddleTable1(Lsmdt.builder()
                    .lsmdTId(UUID.randomUUID().toString().toUpperCase()) //主键
                    .lsmd001(barcode)      //条码编号
                    .lsmd002(dto.getWarehouseCode())      //仓库
                    .lsmd003(dto.getBinCode())//库位
                    .lsmd004(lotNumber)//批号
                    .lsmd005(dto.getMatchQty())//异动数量
                    .lsmd006(-1)//异动类型
                    .lsmd007(dto.getDocNo())//来源单号
                    .lsmd008("0")
                    .lsmd010("0")
                    .lsmd013("admin")//PDA操作人代号
                    .lsmd014(DateUtil.format(date,"yyyy-MM-dd"))//扫描日期
                    .lsmd015(DateUtil.format(date,"HH:mm:ss.SSS"))//时间
                    .lsmd019("Y")//扣账资料否
                    .lsmd024(dto.getUnitNo())//异动数量单位
                    .lsmd025(1.0)//异动与库存单位换算率
                    .lsmd026(SALE_ORDER_OUTSTOCK_APPID)//终端设备编号
                    .lsmd027(SALE_ORDER_OUTSTOCK_APPID+SALE_ORDER_OUTSTOCK_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddHHmmss"))//APP申请串号
                    .lsmd028(SALE_ORDER_OUTSTOCK_APPMODULE)//APP申请所属模组
                    .lsmd029("N")//ERP异动码
                    .lsmd030(dto.getRemark())//备注
                    .lsmd033(UUID.randomUUID().toString().trim().replace("-",""))//APP申请序列号
                    .lsmd034("3002")
                    .lsmd036(binCode)
                    .lsmd037(isLotControlEnabled ? lotNumber : "")
                    .lsmd038("")
                    .lsmd039("002")
                    .lsmd042("YNY")
                    .lsmd045("0.0")
                    .lsmd046(dto.getUnitNo())
                    .lsmd047("0.0")
                    .lsmd053(0.00)
                    .lsmd054("0.00")
                    .lsmd055(0.00)
                    .lsmd058("9998-12-31")
                    .lsmd081("0.0")
                    .lsmd082("0.0")
                    .lsmd083(dto.getItemCode())
                    .lsmd084(UUID.randomUUID().toString().trim().replace("-",""))//字符保留栏位
                    .lsmd085(DateUtil.format(DateUtil.date(),"yyyy-MM-dd"))//过账日期
                    .lsmd086(DateUtil.format(DateUtil.date(),"yyyy-MM-dd"))//日期保留栏位
                    .lsmd906("0")
                    .lsmd907("0")
                    .lsmdcrtdt(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"))//资料创建日
                    .lsmdcrtid("1")//资料建立者
                    .lsmdent(WMS_ENTID)//企业代码
                    .lsmdmoddt(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"))//最近修改日
                    .lsmdmodid("1") //资料修改者
                    .lsmdowndp("qqq") //资料所属部门
                    .lsmdownid("dcms") //资料所有者
                    .lsmdsite(WMS_COMPANYID) //营运据点
                    .lsmdstus("Y") //状态码
                    .build()
            );
            System.out.println("---------------");
        }
        return new MiddleReturnDto(docNo.get(0),SALE_ORDER_OUTSTOCK_APPID,SALE_ORDER_OUTSTOCK_APPID+SALE_ORDER_OUTSTOCK_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddHHmmss"),"zhilink");


    }

    @Override
    public JSONObject SaleOrderOutStockSubmit(MiddleReturnDto middleReturnDto) {
        EtenSession etenSession = new EtenSession(WMS_SUBMIT_KEY,WMS_TYPE,
                new SessionHost(WMS_HOST_PROD,WMS_HOST_IP,WMS_HOST_LANG,WMS_HOST_ACCT, middleReturnDto.getTimestamp(),""),
                new SessionService(WMS_SERVICE_T100,SALE_ORDER_OUTSTOCK_NAME,WMS_SERVICE_IP,WMS_SERVICE_ID),
                new SessionDatakey(WMS_ENTID,WMS_COMPANYID),
                new SessionPayload(new StdData(new ScanToStorageParameter(
                        "","","","","","","","","","","","","","",
                        new ScanToStorageParameterData(
                                "", middleReturnDto.getDocNo(), middleReturnDto.getDocNo(), "","","","","","","","","","","","",""
                        ),
                        new ScanToStorageParameterHost(
                                WMS_HOST_ACCT, middleReturnDto.getTimestamp(), middleReturnDto.getAppid(),SALE_ORDER_OUTSTOCK_APPMODULE,WMS_APPVERSION,SALE_ORDER_OUTSTOCK_NAME,WMS_ENTID,WMS_COMPANYID,middleReturnDto.getErpRemark(),"0",""
                        )
                ))));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type","text/plain; charset=utf-8");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(etenSession), httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(SERVICE_IP_PORT+"/Restful/invokeSrv", httpEntity, String.class);
//        System.out.println(httpEntity);
        System.out.println(response);
        System.out.println(httpEntity.getBody());
        JSONObject result = JSON.parseObject(response);
        return result;
    }

    @Override
    public List<Map<String, Object>> getCoptno(CoptnoDto dto) {
        DynamicDataSourceContextHolder.push(dto.getCompany());

        return saleMapper.getCoptno(dto);

    }

    @Override
    public JSONObject SaleReturnSubmit(MiddleReturnDto middleReturnDto) {
        EtenSession etenSession = new EtenSession(WMS_SUBMIT_KEY,WMS_TYPE,
                new SessionHost(WMS_HOST_PROD,WMS_HOST_IP,WMS_HOST_LANG,WMS_HOST_ACCT, middleReturnDto.getTimestamp(), middleReturnDto.getErpRemark()),
                new SessionService(WMS_SERVICE_T100,SALERETURN_NAME,WMS_SERVICE_IP,WMS_SERVICE_ID),
                new SessionDatakey(WMS_ENTID,WMS_COMPANYID),
                new SessionPayload(new StdData(new ScanToStorageParameter(
                        "","","","","","","","","","","","","","",
                        new ScanToStorageParameterData(
                                "", middleReturnDto.getDocNo(), middleReturnDto.getDocNo(), "","","","","","","","","","","","",""
                        ),
                        new ScanToStorageParameterHost(
                                WMS_HOST_ACCT, middleReturnDto.getTimestamp(), middleReturnDto.getAppid(),SALERETURN_APPMODULE,WMS_APPVERSION,SALERETURN_NAME,WMS_ENTID,WMS_COMPANYID,middleReturnDto.getErpRemark(),"0",""
                        )
                ))));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type","text/plain; charset=utf-8");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(etenSession), httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(SERVICE_IP_PORT+"/Restful/invokeSrv", httpEntity, String.class);
//        System.out.println(httpEntity);
        System.out.println(response);
        System.out.println(httpEntity.getBody());
        JSONObject result = JSON.parseObject(response);
        return result;
    }

    @Override
    public MiddleReturnDto SaleOutStockInsertMiddleTable(List<SaleOutStockDto> list) {
        System.out.println("同步中间表");
        DateTime date = DateUtil.date();
        List<String> docNo = new ArrayList<>();
        String shjg = "";

        for (SaleOutStockDto dto : list) {
            // 查询是否启用了批号管理
            boolean isLotControlEnabled = itemMapper.selectCount(
                    new LambdaQueryWrapper<Item>()
                            .eq(Item::getItemCode, dto.getItemCode())
                            .ne(Item::getLotControl, "N")
            ) > 0;

            // 查询是否启用了库位管理
//            boolean isBinControlEnabled = itemMapper.selectBinControl(dto.getItemCode()) == 1;

//            System.out.println("商品：" + dto.getItemCode() + " 批号管理：" + isLotControlEnabled + " 库位管理：" + isBinControlEnabled);

            // 解析条码
            String barcode = dto.getBarcode();
            docNo.add(dto.getDocNo());

            String binCode = dto.getBinCode();
            String lotNumber= saleMapper.selectLotNumber(dto.getBarcode());

            shjg = dto.getShjg();
            saleMapper.insertMiddleTable1(Lsmdt.builder()
                    .lsmdTId(UUID.randomUUID().toString().toUpperCase()) //主键
                    .lsmd001(barcode)      //条码编号
                    .lsmd002(dto.getWarehouseCode())      //仓库
                    .lsmd003(dto.getBinCode())//库位
                    .lsmd004(lotNumber)//批号
                    .lsmd005(dto.getCurrentNum())//异动数量
                    .lsmd006(-1)//异动类型
                    .lsmd007(dto.getDocNo())//来源单号
                    .lsmd008("0")
                    .lsmd010("0")
                    .lsmd013("admin")//PDA操作人代号
                    .lsmd014(DateUtil.format(date,"yyyy-MM-dd"))//扫描日期
                    .lsmd015(DateUtil.format(date,"HH:mm:ss:SSS"))//时间
                    .lsmd019("Y")//扣账资料否
                    .lsmd024(dto.getUnitCode())//异动数量单位
                    .lsmd025(1.0)//异动与库存单位换算率
                    .lsmd026(SALEOUTSTOCK_APPID)//终端设备编号
                    .lsmd027(SALEOUTSTOCK_APPID+SALEOUTSTOCK_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddHHmmss"))//APP申请串号
                    .lsmd028(SALEOUTSTOCK_APPMODULE)//APP申请所属模组
                    .lsmd029("N")//ERP异动码
                    .lsmd030(dto.getRemark())//备注
                    .lsmd033(UUID.randomUUID().toString().trim().replace("-",""))//APP申请序列号
//                    .lsmd034("2001")
                    .lsmd034("3002")
                    .lsmd036(binCode)
                    .lsmd037(isLotControlEnabled ? lotNumber : "")
                    .lsmd038("")
                    .lsmd039("002")
                    .lsmd042("YNY")
                    .lsmd045("0.0")
                    .lsmd046(dto.getUnitCode())
                    .lsmd047("0.0")
                    .lsmd053(0.00)
                    .lsmd054("0.00")
                    .lsmd055(0.00)
                    .lsmd058("9998-12-31")
                    .lsmd081("0.0")
                    .lsmd082("0.0")
                    .lsmd083(dto.getItemCode())
                    .lsmd084(UUID.randomUUID().toString().trim().replace("-",""))//字符保留栏位
                    .lsmd085(DateUtil.format(DateUtil.date(),"yyyy-MM-dd"))//过账日期
                    .lsmd086(DateUtil.format(DateUtil.date(),"yyyy-MM-dd"))//日期保留栏位
                    .lsmd906("0")
                    .lsmd907("0")
                    .lsmdcrtdt(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"))//资料创建日
                    .lsmdcrtid("1")//资料建立者
                    .lsmdent(WMS_ENTID)//企业代码
                    .lsmdmoddt(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"))//最近修改日
                    .lsmdmodid("1") //资料修改者
                    .lsmdowndp("qqq") //资料所属部门
                    .lsmdownid("dcms") //资料所有者
                    .lsmdsite(shjg) //营运据点
                    .lsmdstus("Y") //状态码
                    .build()
            );
            System.out.println("---------------");
        }
        return new MiddleReturnDto(docNo.get(0),SALEOUTSTOCK_APPID,SALEOUTSTOCK_APPID+SALEOUTSTOCK_APPMODULE+WMS_APPVERSION+DateUtil.format(date,"yyMMddHHmmss"),"zhilink",shjg);

    }

}
